package com.yuanduo_app.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import com.xujl.fastlib.http.DownLoadManager;
import com.xujl.fastlib.http.download.ProgressCallBack;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.fastlib.utils.ToastUtils;
import com.xujl.task.RxExecutor;
import com.xujl.task.RxHelper;

import com.yuanduo_app.R;
import com.yuanduo_app.consts.BundleKey;
import com.yuanduo_app.consts.FileConst;
import com.yuanduo_app.utils.InstallUtils;

import androidx.core.app.NotificationCompat;
import okhttp3.ResponseBody;

/**
 * app更新服务
 */
public class UpdateService extends Service {
    public static final String TAG = "UpdateService";
    public static final String UPDATE_ACTION = "cn.ydxlm.service.update_progress";
    public static final String INSTALL_ACTION = "cn.ydxlm.service.update_install";
    public static final int COMMAND_DOWNLOAD = 0;
    public static final int COMMAND_INSTALL = 1;
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mNoticeBuilder;
    private Notification mNotification;
    private int lastProgress;
    private static final int NOTIFY_ID = 469;
    private String apkVersion;
    private String url;

    @Override
    public IBinder onBind (Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        LogS.d(TAG, "onStartCommand");
        final Bundle bundle = intent.getExtras();
        if (bundle != null) {
            final int command = bundle.getInt(BundleKey.COMMAND);
            if (command == COMMAND_INSTALL) {
//                install(this, FileConst.UPDATE_PATH + apkVersion + FileConst.UPDATE_APK);
                return super.onStartCommand(intent, flags, startId);
            }
            url = bundle.getString(BundleKey.URL);
            apkVersion = bundle.getString(BundleKey.VERSION);
            if (!StringUtils.isEmpty(url)) {
                downloadNewApk(url);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    public void downloadNewApk (String url) {
        LogS.d(TAG, "downloadNewApk：" + url);
        initNotification();
        DownLoadManager.getInstance().load(url, new ProgressCallBack<ResponseBody>(FileConst.UPDATE_PATH, FileConst.UPDATE_APK) {
            @Override
            public void onSuccess (ResponseBody body) {
                LogS.d(TAG, "下载完成");
                RxExecutor.getInstance().executeTask(new RxHelper.DelayTask(2000) {
                    @Override
                    public void timeOver () {
                        startInstall();
                        final Intent intent = new Intent();
                        intent.setAction(UPDATE_ACTION);
                        intent.putExtra(BundleKey.DATA, 100);
                        sendBroadcast(intent);
                    }
                });
            }

            @Override
            public void progress (long progress, long total) {
                try {
                    int process = (int) (((float) progress / (float) total) * 100f);
                    if (process - lastProgress < 1) {
                        return;
                    }
                    LogS.d(TAG, "process" + process + "% &&progress:" + progress + " && total:" + total);
                    lastProgress = process;
                    mNoticeBuilder.setProgress(100, process, false);
                    mNoticeBuilder.setContentText("下载进度:" + process + "%");
                    mNotification = mNoticeBuilder.build();
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    final Intent intent = new Intent();
                    intent.setAction(UPDATE_ACTION);
                    intent.putExtra(BundleKey.DATA, process);
                    sendBroadcast(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError (Throwable e) {
                LogS.d(TAG, "下载中断：" + e.getMessage());
                ToastUtils.toast("文件下载中断...");
            }
        });
    }

    private void startInstall () {
        PendingIntent pi = PendingIntent.getActivity(UpdateService.this, 0, InstallUtils.getInstallIntent(this), 0);
        mNoticeBuilder.setContentTitle("下载完成")
                .setContentText("点击安装")
                .setProgress(100, 100, false)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setContentIntent(pi);
        mNotification = mNoticeBuilder.build();
        mNotificationManager.notify(NOTIFY_ID, mNotification);
        install(this);
    }

    public static void install (Context context) {
//        Intent intent = new Intent(context, UpdateService.class);
//        final Bundle bundle = new Bundle();
//        bundle.putInt(BundleKey.COMMAND, UpdateService.COMMAND_INSTALL);
//        intent.putExtras(bundle);
//        context.startService(intent);
        final Intent intent = new Intent();
        intent.setAction(INSTALL_ACTION);
        context.sendBroadcast(intent);
    }


    private void initNotification () {
        String channelId = null;
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = "缘多新联盟";
            NotificationChannel channel = new NotificationChannel(channelId,
                    "缘多新联盟", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.RED); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
//            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
        mNoticeBuilder = new NotificationCompat.Builder(this, channelId);
        mNoticeBuilder.setContentTitle("正在更新...") //设置通知标题
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) //设置通知的大图标
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setOnlyAlertOnce(true)
                .setContentText("下载进度:" + "0%")
                .setProgress(100, 0, false);
        mNotification = mNoticeBuilder.build();//构建通知对象
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }
}
